<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Inertia\Inertia;

class FollowController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * 关注用户
     */
    public function follow(User $user)
    {
        $currentUser = auth()->user();

        if ($currentUser->id === $user->id) {
            return back()->with('error', '不能关注自己');
        }

        $currentUser->follow($user);

        return back()->with('success', '关注成功');
    }

    /**
     * 取消关注用户
     */
    public function unfollow(User $user)
    {
        $currentUser = auth()->user();
        $currentUser->unfollow($user);

        return back()->with('success', '取消关注成功');
    }

    /**
     * 获取关注列表
     */
    public function following(User $user)
    {
        $following = $user->following()
            ->withCount(['followers', 'following', 'posts'])
            ->paginate(20);

        return Inertia::render('Profile/Following', [
            'user' => $user->load(['followers', 'following']),
            'following' => $following,
            'isOwnProfile' => auth()->id() === $user->id,
        ]);
    }

    /**
     * 获取粉丝列表
     */
    public function followers(User $user)
    {
        $followers = $user->followers()
            ->withCount(['followers', 'following', 'posts'])
            ->paginate(20);

        return Inertia::render('Profile/Followers', [
            'user' => $user->load(['followers', 'following']),
            'followers' => $followers,
            'isOwnProfile' => auth()->id() === $user->id,
        ]);
    }
}